<template>
  <div class="avator-container">
    <img ref="img" :src=img>
    <div class="toobal">
      <span @click="$emit('close')">取消</span>
      <span @click="onConfirm">完成</span>
    </div>
  </div>
</template>

<script>
// 引入裁剪工具
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
// 导入接口
import { changeUserPhoto } from '@/api/user.js'
export default {
  props: {
    img: {
      type: [String, Object],
      require: true
    }
  },
  name: 'UpdateAvator',
  data () {
    return {
      myCropper: null
    }
  },
  methods: {
    // 提交完成
    onConfirm () {
      // console.log(this.myCropper.getData())
      // 客户端
      this.myCropper.getCroppedCanvas().toBlob(async blob => {
        // console.log(blob)

        // 创建formDate数据
        const formDate = new FormData()
        formDate.append('photo', blob)

        this.$toast.loading({
          duration: 0, // 持续展示toast
          message: '修改中',
          forbidclick: 'true' // 禁止点击背景
        })

        try {
          const { data: res } = await changeUserPhoto(formDate)
          console.log(res)
          this.$emit('updateAvator', res.data.photo)
          this.$emit('close')
          this.$toast('修改成功')
        } catch (err) {
          this.$toast('修改失败，请重试')
        }
      })
    },
    // 初始化裁剪工具
    init () {
      const image = this.$refs.img
      // console.log(image)
      // 配置cropperjs
      this.myCropper = new Cropper(image, {
        viewMode: 1, // 只能在裁剪的图片范围内移动
        dragMode: 'move', // 画布和图片都可以移动
        aspectRatio: 1, // 裁剪区默认正方形
        autoCropArea: 1, // 自动调整裁剪图片
        cropBoxMovable: false, // 禁止裁剪区移动
        cropBoxResizable: false, // 禁止裁剪区缩放
        background: false // 关闭默认背景
      })
    }
  },
  computed: {},
  watch: {},
  filters: {},
  components: {},
  created () { },
  mounted () {
    this.init()
  }
}
</script>

<style lang='less' scoped>
.avator-container {
  background-color: #000;
  width: 100%;
  height: 100%;
  .toobal {
    position: fixed;
    bottom: 10px;
    display: flex;
    justify-content: space-between;
    width: 100%;
    padding: 0 15px;
    color: #fff;
    font-size: 28px;
    box-sizing: border-box;
  }
}
</style>
